package com.ruoyi.cm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.cm.domain.CmBsContractInfoMilestone;
import com.ruoyi.cm.domain.CmBsContractInfoScene;
import com.ruoyi.cm.domain.CmBsStartAdvance;
import com.ruoyi.cm.mapper.CmBsContractInfoMilestoneMapper;
import com.ruoyi.cm.mapper.CmBsContractInfoSceneMapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import com.ruoyi.cm.domain.bo.CmBsContractInfoBo;
import com.ruoyi.cm.domain.vo.CmBsContractInfoVo;
import com.ruoyi.cm.domain.CmBsContractInfo;
import com.ruoyi.cm.mapper.CmBsContractInfoMapper;
import com.ruoyi.cm.service.ICmBsContractInfoService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 合同管理Service业务层处理
 *
 * @author zyb
 * @date 2024-09-27
 */
@RequiredArgsConstructor
@Service
public class CmBsContractInfoServiceImpl implements ICmBsContractInfoService {

    private final CmBsContractInfoMapper baseMapper;

    private final CmBsContractInfoSceneMapper sceneMapper;

    private final CmBsContractInfoMilestoneMapper milestoneMapper;
    private final TaskService taskService;
    private final ISysUserService userService;
    @Resource
    protected HistoryService historyService;

    /**
     * 查询合同管理
     */
    @Override
    public CmBsContractInfoVo queryById(Long contractId){
        return baseMapper.selectVoById(contractId);
    }

    /**
     * 查询合同管理列表
     */
    @Override
    public TableDataInfo<CmBsContractInfoVo> queryPageList(CmBsContractInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CmBsContractInfo> lqw = buildQueryWrapper(bo);
        Page<CmBsContractInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //查询合同场景表
        List<CmBsContractInfoVo> records = result.getRecords();
        if(CollUtil.isNotEmpty(records)){
            Long contractId = records.get(0).getContractId();
            List<CmBsContractInfoScene> sceneList =
                sceneMapper.selectList(new LambdaQueryWrapper<CmBsContractInfoScene>().eq(CmBsContractInfoScene::getContractId,contractId));
            records.get(0).setSceneList(sceneList);
            // 根据流程实例id获取任务id
            records.forEach(item -> {
                if (ObjectUtils.isNotEmpty(item.getProcInsId())) {
                    Task task = taskService.createTaskQuery().processInstanceId(item.getProcInsId()).singleResult();
                    if (task != null) {
                        item.setTaskId(task.getId());
                        if (task.getAssignee() != null && (Long.valueOf(task.getAssignee()) == LoginHelper.getUserId())) {
                            item.setCurrApproval(true);
                        } else {
                            item.setCurrApproval(false);
                        }
                    }
                }
                if (ObjectUtils.isNotEmpty(item.getChgProcInsId())) {
                    Task task = taskService.createTaskQuery().processInstanceId(item.getChgProcInsId()).singleResult();
                    if (task != null) {
                        item.setChgTaskId(task.getId());
                        if (task.getAssignee() != null && (Long.valueOf(task.getAssignee()) == LoginHelper.getUserId())) {
                            item.setCurrApproval(true);
                        } else {
                            item.setCurrApproval(false);
                        }
                    }
                }
            });

        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询合同管理列表
     */
    @Override
    public List<CmBsContractInfoVo> queryList(CmBsContractInfoBo bo) {
        LambdaQueryWrapper<CmBsContractInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CmBsContractInfo> buildQueryWrapper(CmBsContractInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CmBsContractInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getProjectId() != null, CmBsContractInfo::getProjectId, bo.getProjectId());
        lqw.eq(bo.getBdId() != null, CmBsContractInfo::getBdId, bo.getBdId());
        lqw.eq(StringUtils.isNotBlank(bo.getContractNum()), CmBsContractInfo::getContractNum, bo.getContractNum());
        lqw.eq(StringUtils.isNotBlank(bo.getContractType()), CmBsContractInfo::getContractType, bo.getContractType());
        lqw.like(StringUtils.isNotBlank(bo.getContractName()), CmBsContractInfo::getContractName, bo.getContractName());
        lqw.eq(bo.getSignDate() != null, CmBsContractInfo::getSignDate, bo.getSignDate());
        lqw.eq(bo.getRongliang() != null, CmBsContractInfo::getRongliang, bo.getRongliang());
        lqw.eq(bo.getDanjia() != null, CmBsContractInfo::getDanjia, bo.getDanjia());
        lqw.eq(bo.getContractAmount() != null, CmBsContractInfo::getContractAmount, bo.getContractAmount());
        lqw.eq(bo.getPartADeptId() != null, CmBsContractInfo::getPartADeptId, bo.getPartADeptId());
        lqw.like(StringUtils.isNotBlank(bo.getPartAName()), CmBsContractInfo::getPartAName, bo.getPartAName());
        lqw.eq(bo.getPartBDeptId() != null, CmBsContractInfo::getPartBDeptId, bo.getPartBDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getPartBName()), CmBsContractInfo::getPartBName, bo.getPartBName());
        lqw.eq(StringUtils.isNotBlank(bo.getPayStatus()), CmBsContractInfo::getPayStatus, bo.getPayStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getApprovalStatus()), CmBsContractInfo::getApprovalStatus, bo.getApprovalStatus());
        lqw.eq(bo.getBeginDate() != null, CmBsContractInfo::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getEndDate() != null, CmBsContractInfo::getEndDate, bo.getEndDate());
        lqw.eq(bo.getKcjljjbl() != null, CmBsContractInfo::getKcjljjbl, bo.getKcjljjbl());
        lqw.eq(bo.getKgyfkbl() != null, CmBsContractInfo::getKgyfkbl, bo.getKgyfkbl());
        lqw.eq(bo.getProcInsId() != null, CmBsContractInfo::getProcInsId, bo.getProcInsId());
        lqw.eq(bo.getChgProcInsId() != null, CmBsContractInfo::getChgProcInsId, bo.getChgProcInsId());
        return lqw;
    }

    /**
     * 新增合同管理
     */
    @Override
    public Boolean insertByBo(CmBsContractInfoBo bo) {
        CmBsContractInfo add = BeanUtil.toBean(bo, CmBsContractInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setContractId(add.getContractId());
            //新增合同建设场景子表；
            List<CmBsContractInfoScene> sceneList = bo.getSceneList();
            sceneList.forEach(e->e.setContractId(bo.getContractId()));
            sceneMapper.insertOrUpdateBatch(sceneList);
        }
        return flag;
    }

    /**
     * 修改合同管理
     */
    @Override
    public Boolean updateByBo(CmBsContractInfoBo bo) {
        CmBsContractInfo update = BeanUtil.toBean(bo, CmBsContractInfo.class);
        validEntityBeforeSave(update);
        boolean flag =  baseMapper.updateById(update) > 0;
        //更新子表；
        if(flag){
            //先删除
            sceneMapper.deleteByContractId(bo.getContractId());
            List<CmBsContractInfoScene> sceneList = bo.getSceneList();
            sceneList.forEach(e->e.setContractId(bo.getContractId()));
            sceneMapper.insertOrUpdateBatch(sceneList);
        }
        return flag;
    }

    /**
     * 修改合同管理
     */
    @Override
    public Boolean updateApprovalStatusByBo(CmBsContractInfoBo bo) {
        LambdaUpdateWrapper<CmBsContractInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.set(bo.getApprovalStatus() != null, CmBsContractInfo :: getApprovalStatus,bo.getApprovalStatus());
        lambdaUpdateWrapper.set(bo.getProcInsId() != null, CmBsContractInfo :: getProcInsId,bo.getProcInsId());
        lambdaUpdateWrapper.eq(CmBsContractInfo :: getBdId,bo.getBdId());
        baseMapper.update(null,lambdaUpdateWrapper);
        LambdaUpdateWrapper<CmBsContractInfoMilestone> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
        lambdaUpdateWrapper1.set(bo.getApprovalStatus() != null, CmBsContractInfoMilestone :: getApprovalStatus,bo.getApprovalStatus());
        lambdaUpdateWrapper1.set(bo.getProcInsId() != null, CmBsContractInfoMilestone :: getProcInsId,bo.getProcInsId());
        lambdaUpdateWrapper1.eq(CmBsContractInfoMilestone :: getContractId,bo.getContractId());
        return milestoneMapper.update(null,lambdaUpdateWrapper1)>0;
    }
    /**
     * 修改合同管理
     */
    @Override
    public Boolean updateChgApprovalStatusByBo(CmBsContractInfoBo bo) {
        LambdaUpdateWrapper<CmBsContractInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.set(bo.getChgApprovalStatus() != null, CmBsContractInfo :: getChgApprovalStatus,bo.getChgApprovalStatus());
        lambdaUpdateWrapper.set(bo.getChgProcInsId() != null, CmBsContractInfo :: getChgProcInsId,bo.getChgProcInsId());
        lambdaUpdateWrapper.eq(CmBsContractInfo :: getBdId,bo.getBdId());
        return baseMapper.update(null,lambdaUpdateWrapper)>0;
//        LambdaUpdateWrapper<CmBsContractInfoMilestone> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
//        lambdaUpdateWrapper1.set(CmBsContractInfoMilestone :: getApprovalStatus,bo.getApprovalStatus());
//        lambdaUpdateWrapper1.eq(CmBsContractInfoMilestone :: getContractId,bo.getContractId());
//        return milestoneMapper.update(null,lambdaUpdateWrapper1)>0;
    }
    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CmBsContractInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除合同管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Map<String, Object> getApprovalStatus(String bdId) {
        return null;
    }
}
